﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WeiTap.Web.BodyParsers
{
    /// <summary>
    /// JSON格式
    /// </summary>
    public sealed class HttpJsonBodyParser : HttpBodyParserBase
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="formatProvider"></param>
        /// <returns></returns>
        public override IEnumerable<KeyValuePair<string, object>> Deserialize(byte[] bytes, IFormatProvider formatProvider)
        {
            var encoding = GetEncoding(formatProvider);
            var json = encoding.GetString(bytes);
            return Newtonsoft.Json.JsonConvert.DeserializeObject<IDictionary<string, object>>(json);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public override bool IsMatch(string type, string format)
        {
            return format?.Length == 4 && format.EndsWith("json", StringComparison.OrdinalIgnoreCase);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="format"></param>
        /// <param name="body"></param>
        /// <param name="formatProvider"></param>
        /// <returns></returns>
        public override byte[] Serialize(string format, IEnumerable<KeyValuePair<string, object>> body, IFormatProvider formatProvider)
        {
            string json;
            if (body == null) json = string.Empty;
            else if (body.Count() == 1 && body.FirstOrDefault().Key == null)
                json = Newtonsoft.Json.JsonConvert.SerializeObject(body.FirstOrDefault().Value);
            else
            {
                json = Newtonsoft.Json.JsonConvert.SerializeObject(body);
            }
            var charset = GetEncoding(formatProvider) ?? Encoding.UTF8;
            return charset.GetBytes(json);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bytes"></param>
        /// <param name="formatProvider"></param>
        /// <returns></returns>
        public override T Deserialize<T>(byte[] bytes, IFormatProvider formatProvider)
        {
            var encoding = GetEncoding(formatProvider);
            var json = encoding.GetString(bytes);
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
        }
    }
}
